﻿// Our default grid options
var defaultGridOptions = {
    enableCellNavigation: true,
    enableColumnReorder: false,
    enableAddRow: false,
    editable: true,
    editOnDoubleClick: true,
    multiSelect: false,
    forceFitColumns: false,
    autoHeight: false,
    resizable: false,
    autoEdit: false,
    showHeaderRow: true,
    rowHeight: 36,
    headerHeight: 36,
    headerRowHeight: 36

};

$().ready(
    function () {
        $('.button').button();
        $('.Avail_Times').timepicker({
            showCloseButton: true,
            minutes: {
                starts: 0,                // First displayed minute
                ends: 59,                 // Last displayed minute
                interval: 15                // Interval of displayed minutes
            },
            showPeriod: true,
            onHourShow: OnHourShowCallback,
            onMinuteShow: OnMinuteShowCallback,
            defaultTime: '12:00'
        });

        function OnHourShowCallback(hour) {
            if (this.name == "From" && $to.val() != '') {
                if (hour >= $to.timepicker('getHour')) {
                    return false; // not valid
                }
            } else if (this.name == "To" && $from.val() != '') {
                if (hour <= $from.timepicker('getHour')) {
                    return false; // not valid
                }

            }
            return true;
        }

        function OnMinuteShowCallback(hour, minute) {
            if ((hour == 20) && (minute >= 30)) {
                return false;
            } // not valid
            if ((hour == 6) && (minute < 30)) {
                return false;
            } // not valid
            return true; // valid
        }

        $('#applicationAdd').click(function (e) {
            e.preventDefault();
            var data = {};
            $('#addApplicationForm input').each(function (i, element) {
                data[element.name] = element.value;
            });
            $.post('/ManagementJobApplication/create', data, function (response) {
                if (response.Result) {

                } else {
                    alert(response.Data);
                }
            });

        });
        setUpApplicationsGrid();
        // Sets up the sample grid

        function setUpApplicationsGrid() {
            // First, define the grid's columns
            var $gridSelector = $('#applicationsGrid');

            function nameFormatter(row, cell, value, columnDef, dataContext) {
                return dataContext.FirstName + " " + dataContext.MiddleName + " " + dataContext.LastName;
            }

            var columns = [
                { id: "Name", name: "Name", field: "", width: 350, sortable: true, formatter: nameFormatter },
                { id: "Telephone", name: "Phone Number", field: "Telephone", width: 200, sortable: true },
                { id: "buttons", name: "", field: "", width: 390, sortable: false, formatter: CellButtonFormatter, buttons: ["View", "Delete"] }
            ];


            // Set some additional options
            var options = $.extend(true, {}, defaultGridOptions);
            options.hasHeaderFilters = true;

            // Create the grid
            var grid = new Slick.Grid($gridSelector, [], columns, options);
            grid.registerPlugin(new Slick.ExtendedGrid($gridSelector, columns, options));
            grid.updateHeaderRow();

            // Make the grid buttons use jQuery UI
            grid.onRender.subscribe(function (e, args) {
                $('.slick-cell-button').button();
            });
            block({ element: $gridSelector, text: 'Loading' });
            $.getJSON('/ManagementJobApplication/List', function (response) {
                if (response.Result)
                    grid.dataView.setItems(response.Data);
                else {
                    alert(response.Data);
                }
            }).complete(function () {
                unblock({ element: $gridSelector });
            });
            var dialog = setUpAddApplicationDialog();
            setUpDeleteApplicationDialog();

            // Return the grid object so we can store it in a variable
            return grid;

            function setUpAddApplicationDialog() {
                var $dialog = $('#addApplicationDialog');
                var $form = $('#addApplicationForm');
                $dialog.dialog({
                    modal: true,
                    resizable: false,
                    autoOpen: false,
                    width: 1024,
                    height: 785,
                    buttons:
                        {
                            OK: function () {
                                var $this = $(this);
                                // Show a saving indicator
                                block({ element: $this.parent(), text: 'Saving' });
                                var data = extractFormData($form);
                                // Post to the server
                                $.post('/ManagementJobApplication/Create',
                                // Set up the data to transfer
                                    data,
                                // This function gets called if the server successfully returns a response. 
                                // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                                    function (response) {
                                        if (response.Result) {
                                            // If the request succeeded, display the changes
                                            if (data.Id)
                                                grid.dataView.updateItem(data.Id, data);
                                            else {
                                                data.Id = response.Data;
                                                grid.dataView.addItem(data);
                                            }
                                            
                                            // Clear the fields
                                            clearForm($('#addApplicationForm'));
                                            // Close the dialog box
                                            $dialog.dialog('close');
                                        } else {
                                            // If it failed, show the error response
                                            alert(response.Data);
                                        }
                                    }).error(function () {

                                        // Let the user know an error occurred.
                                        alert("An error occurred while saving your info. Please refresh the page and try again.");
                                    }).complete(function () {
                                        // Remove the "saving" block
                                        unblock({ element: $this.parent() });

                                    });

                            },
                            Cancel:
                                function () {
                                    // Clear the fields
                                    clearForm($('#addApplicationForm'));

                                    // Close the dialog box
                                    $(this).dialog('close');
                                }
                        }
                });

                $('#addApplication').click(function () {
                    $dialog.dialog('open');
                });
                $(document).on('click', '.slick-cell-button-View', function () {

                    var data = grid.getDataItem(grid.getActiveCell().row);
                    $form.find('input, select').each(function () {
                        var $this = $(this);
                        if ($this.is('[type="checkbox"]')) {
                            if (data[this.name] == true)
                                $this.attr('checked', 'checked');
                        } else
                            $this.val(data[this.name]);
                    });
                    $dialog.dialog('open');

                });
            }

            function setUpDeleteApplicationDialog() {
                var $dialog = $('#deleteApplicationDialog');
                $dialog.dialog({
                    modal: true,
                    resizable: false,
                    autoOpen: false,
                    width: 400,
                    buttons:
                {
                    OK: function () {
                        var $this = $(this);
                        // Show a saving indicator
                        block({ element: $this, text: 'Saving' });
                        var id = grid.getDataItem(grid.getActiveCell().row).Id;
                        // Post to the server
                        $.post('/ManagementJobApplication/Delete',
                        // Set up the data to transfer
                            {id: id },
                        // This function gets called if the server successfully returns a response. 
                        // This does not mean that no errors occurred; it means that no unhandled errors occurred.
                            function (response) {
                                if (response.Result) {
                                    // If the request succeeded, display the changes
                                    grid.dataView.deleteItem(id);
                                } else {
                                    // If it failed, show the error response
                                    alert(response.Data);
                                }
                                unblock({ element: $this });

                                // Close the dialog
                                $this.dialog('close');
                            }).error(function () {
                                // Remove the "saving" block
                                unblock({ element: $this });
                                // Let the user know an error occurred.
                                alert("An error occurred while saving your info. Please refresh the page and try again.");
                            });

                    },
                    Cancel:
                        function () {
                            // Close the dialog box
                            $(this).dialog('close');
                        }
                }
                });
                $(document).on('click', $gridSelector.selector + ' .slick-cell-button-Delete', function () {

                    var row = grid.getDataItem(grid.getActiveCell().row);
                    //            debugger;
                    $('#applicationName').text(row.FirstName + " " + row.MiddleName + " " + row.LastName);
                    $dialog.dialog('open');
                });
            }
        }
    });

        
    
